const pool = require('../utils/utils.js')
var dayjs = require('dayjs')

const regist = async (ctx, next)=>{
    console.log(ctx.request.body)
    const {nickName,password,role} = ctx.request.body;
    if(nickName && password){ 
         // 先检查下有没有注册过
         let selectStr = 'SELECT * FROM' + "`user` " + 'where nickname= "' + nickName + '"'
         console.log(selectStr)
         let r = await new Promise((resolve, reject) => {
             pool.query(selectStr, (err, result) => {
                 if (err) {
                     reject(err)
                 } else {
                     resolve(result)
                 }
             })
         })
         if(Array.isArray(r) && r.length===0){
            let roleStr =  role ? JSON.stringify(role) : '1'
           let queryStr = "INSERT INTO user (nickname,`password`,registtime,role) VALUES (" + JSON.stringify(nickName) + "," + JSON.stringify(password) + "," + JSON.stringify(dayjs().format())+ "," + roleStr + ")"
            console.log(queryStr)
            let res = await new Promise((resolve, reject) => {
                pool.query(queryStr, (err, result) => {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(result)
                    }
                })
            })
            ctx.body = {
                code:0,
                msg:'注册成功'
            }
         }else{
            ctx.body = {
                code:400,
                msg:'用户名已被占用'
            }
         }
        
    }else{
        ctx.body={
            code:400,
            msg:'参数错误'
        }
    }
    await next()
}

module.exports = regist